package cn.yuanqiao.archive.detection.util;

import cn.hutool.core.io.IoUtil;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.mapper.TenantCateMdataListMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ITenantCodelistService;
import cn.yuanqiao.archive.detection.domain.DetailLogs;
import cn.yuanqiao.archive.detection.domain.DetectionFile;
import cn.yuanqiao.archive.detection.domain.DetectionItem;
import cn.yuanqiao.archive.detection.mapper.DetectionObjectMapper;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import com.lowagie.text.pdf.PdfReader;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class DetectionUtil {

    @Autowired
    private DetectionObjectMapper detectionObjectMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;

    @Autowired
    private ITenantCodelistService tenantCodelistService;

    @Value("${is_zt}")
    private String isZt;

    public String getDhLj(String type, String rq, Long categoryId) {
        List<Map> list1 = new ArrayList<>();
        if (!StringUtils.isEmpty(rq)) {
            if ("[]".equals(rq)) {
                rq = "";
            }
        }
        if (StringUtils.isNotEmpty(rq)) {
            rq = rq.replaceAll("-", "").replaceAll("/", "");
            ;
            rq = addZero(rq);
        }
        if (!StringUtils.isEmpty(rq)) {
            list1 = detectionObjectMapper.getDhByRq(rq, SecurityUtils.getLoginUser().getSysUser().getTenantCode().toUpperCase(), categoryId);
        }

        if (list1.size() <= 0) {
            list1 = detectionObjectMapper.getDh(rq, SecurityUtils.getLoginUser().getSysUser().getTenantCode().toUpperCase(), categoryId);
        }
        com.alibaba.fastjson2.JSONObject json = tenantCodelistService.getdetail(type, Long.parseLong(list1.get(0).get("RULEID").toString()));

        if ("v".equals(type)) {
            return json.getString("jianlianjie")+";&"+ json.get("jianbuling");
        } else {
            return "";
        }
    }
    //固化信息有效性检测
    public boolean detection1() {

        return true;
    }


    public boolean verifyNumber(String value) {

        String reg = "^-?[0-9]+(.[0-9]+)?$";
        return value.matches(reg);
    }

    public boolean checkDataType(Object object) {
        boolean flag = true;
        Pattern p = Pattern.compile("^((\\d{2}(([02468][048])|([13579][26]))[\\.\\-\\/\\s]?((((0?[13578])|(1[02]))[\\.\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\.\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\.\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\.\\-\\/\\s]?((((0?[13578])|(1[02]))[\\.\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\.\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\.\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1][0-9])|([2][0-4]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        flag = p.matcher(object.toString()).matches();
        return flag;
    }

    public boolean regStr(String str) {
        str = str.replace("[", "").replace("]", "").replace("\"", "").replace("“", "").replace("”", "");
        String regEx = "[^\\u4e00-\\u9fa5\\x00-\\xff]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return !m.find();
    }

    public List<String> checkDh(Long categoryId, Integer type, String rq, net.sf.json.JSONObject jsonObject, String fileName, String dhValue,
                                net.sf.json.JSONObject jianJson) {
        List list = new ArrayList();
        //获取规则项然后去获取值
        List<Map> list1 = new ArrayList<>();
        if (!StringUtils.isEmpty(rq)) {
            if ("[]".equals(rq)) {
                rq = "";
            }
        }
        if (StringUtils.isNotEmpty(rq)) {
            rq = rq.replaceAll("-", "").replaceAll("/", "");
            ;
            rq = addZero(rq);
        }
        if (!StringUtils.isEmpty(rq)) {
            list1 = detectionObjectMapper.getDhByRq(rq, SecurityUtils.getLoginUser().getSysUser().getTenantCode().toUpperCase(), categoryId);
        }

        if (list1.size() <= 0) {
            list1 = detectionObjectMapper.getDh(rq, SecurityUtils.getLoginUser().getSysUser().getTenantCode().toUpperCase(), categoryId);
        }
        //组件只需要验证档号字段即可
        if (list1.size() <= 0) {
            list.add("该档案未设置档号规则");
        } else {
            String lx = "";
            if (type.equals(0)) {
                lx = "f";
            } else if (type.equals(1) || type.equals(2)|| type.equals(3)) {
                lx = "v";
            }
            List dhList = new ArrayList();
            List jdhList = new ArrayList();
            for (Map map : list1) {
                //获取值
                TenantMdataList mdataList = new TenantMdataList();
                mdataList.setCategoryId(categoryId);
                mdataList.setFieldName(map.get("NODEVALUE").toString());
                mdataList.setType( map.get("TYPE").equals("f")?0:1);
                List<TenantMdataList> tenantMdataLists = this.getSchemelist(mdataList);
                if ("v".equals(lx) && map.get("TYPE").equals("f")) {
                    if (type.equals(2)) {
                        String str = jsonObject.getString("件档号组成字段");
                        if (jianJson.has(str)) {
                            jdhList.add(jianJson.getString(str));

                        } else {
                            list.add(str + "不存在！");
                            return list;

                        }
                    }
                } else {
                    String name = tenantMdataLists.get(0).getFieldCaption();
                    if (jsonObject.has(name)) {
                        dhList.add(jsonObject.getString(name));
                    } else {
                        list.add(name + "不存在！");
                        return list;

                    }
                }

            }
            if(type.equals(2)){
                dhList.add(jdhList);
            }
            com.alibaba.fastjson2.JSONObject json = tenantCodelistService.getdetail(lx, Long.parseLong(list1.get(0).get("RULEID").toString()));
            //获取档号值
            List ziduanarr = (List) json.get("ziduanarr");
            List fuhaoarr = (List) json.get("fuhaoarr");
            List bulingarr = (List) json.get("bulingarr");
            String dh = "";
            if (type.equals(0) || type.equals(1) || type.equals(3)) {
                //获取值拼接
                for (int i = 0; i < ziduanarr.size(); i++) {
                    String field = ziduanarr.get(i).toString();
                    //获取值
                    String value = dhList.get(i).toString();
                    int length = value.length();
                    if (i == (ziduanarr.size() - 1)) {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {

                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value;

                    } else {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value + fuhaoarr.get(i);
                    }

                }
                if (!dh.equals(dhValue)) {
                    list.add("档号字段不符合档号规则");
                }

            } else if (type.equals(2)) {
                //卷内件
                // daId=detectionObjectMapper.getFolderIdByDaId(daId,SecurityUtils.getTenantCode().toUpperCase());
                String jianlianjie = json.getString("jianlianjie");
                String jianziduan = json.getString("jianziduan");
                String jianbuling = json.getString("jianbuling");
                //获取值拼接
                for (int i = 0; i < ziduanarr.size(); i++) {//获取值
                    //通过daId获取folderId
                    String value = dhList.get(i).toString();
                    int length = value.length();
                    if (i == (ziduanarr.size() - 1)) {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value;

                    } else {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - value.length()); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value + fuhaoarr.get(i);
                    }

                }
                //拼接最后一位
                dh += jianlianjie;
              /*  String jianValue=dhList.get(dhList.size()-1).toString();;
                int jianLegth=jianValue.length();
                if(Integer.parseInt(jianbuling)>0){
                    if(jianValue.length()<Integer.parseInt(jianbuling)){
                        for(int j=0;j<(Integer.parseInt(jianbuling)-jianLegth);j++){
                            jianValue="0"+jianValue;
                        }
                    }
                }
                dh+=jianValue;*/
                if (dhValue.indexOf(dh) < 0) {
                    list.add("档号字段不符合档号规则");
                }


            }


        }


        return list;
    }

    /**
     * 元数据项连续性检测 暂时检测件号和卷连续性
     *
     * @return
     */
    public List<DetailLogs> checkISContinuous(List juanlist, List jianlist, List dhList, List parentDhList, Long pId, Long dId, String checkType) {
        boolean flag = true;
        List<DetailLogs> detailLogsList = new ArrayList<>();
        if (juanlist.size() > 1) {
            Object[] array = juanlist.toArray();
            Arrays.sort(array);
            int index = Integer.parseInt(array[0].toString());
            for (int i = 1; i < array.length; i++) {
                if ((Integer.parseInt(array[i].toString()) - index) != 1) {
                    DetailLogs detailLogs = new DetailLogs();
                    detailLogs.setId(SnowflakeIdGenerator.generateId());
                    detailLogs.setpId(pId);
                    detailLogs.setDetectionTime(DateUtils.getNowDate());
                    detailLogs.setCheckType(checkType);
                    String message = "";
                    if ("1".equals(checkType)) {
                        message = "案卷号";
                    } else if ("0".equals(checkType)) {
                        message = "件号";

                    }
                    detailLogs.setMessage(message + index + "," + Integer.parseInt(array[i].toString()) + "之间不连续");
                    detailLogs.setCheckDh(dhList.get(i) == null ? "" : dhList.get(i).toString());
                    if (parentDhList.size() > 0) {
                        detailLogs.setCheckParentDh(parentDhList.get(i) == null ? "" : parentDhList.get(i).toString());
                    }
                    detailLogs.setdId(dId);
                    detailLogsList.add(detailLogs);
                    index = Integer.parseInt(array[i].toString());

                } else {
                    index = Integer.parseInt(array[i].toString());
                }
            }
        }
        if (jianlist.size() > 1) {
            Object[] array = jianlist.toArray();
            Arrays.sort(array);
            int index = Integer.parseInt(array[0].toString());
            for (int i = 1; i < array.length; i++) {
                if ((Integer.parseInt(array[i].toString()) - index) != 1) {
                    DetailLogs detailLogs = new DetailLogs();
                    detailLogs.setId(SnowflakeIdGenerator.generateId());
                    detailLogs.setpId(pId);
                    detailLogs.setDetectionTime(DateUtils.getNowDate());
                    detailLogs.setCheckType(checkType);
                    String message = "";
                    if ("1".equals(checkType)) {
                        message = "案卷号";
                    } else if ("0".equals(checkType)) {
                        message = "件号";

                    }
                    detailLogs.setMessage(message + index + "," + Integer.parseInt(array[i].toString()) + "之间不连续");
                    detailLogs.setCheckDh(dhList.get(i) == null ? "" : dhList.get(i).toString());
                    if (parentDhList.size() > 0) {
                        detailLogs.setCheckParentDh(parentDhList.get(i) == null ? "" : parentDhList.get(i).toString());
                    }
                    detailLogs.setdId(dId);
                    detailLogsList.add(detailLogs);
                    index = Integer.parseInt(array[i].toString());
                } else {
                    index = Integer.parseInt(array[i].toString());
                }
            }
        }

        return detailLogsList;
    }

    public int checkRepeatability(String subTableName, String fieldName, String value) {

        return detectionObjectMapper.getCountByDetection(subTableName, fieldName, SecurityUtils.getTenantCode().toUpperCase(), value);
    }
    public int checkRepeatabilityByCode(String subTableName, String fieldName, String value,String code) {

        return detectionObjectMapper.getCountByDetection(subTableName, fieldName, code.toUpperCase(), value);
    }

    public List verifyFormat(List<DetectionItem> detectionItems, String path) {
        Set set = new HashSet();
        String name1 = "";
        for (DetectionItem detectionItem : detectionItems) {
            String name = detectionItem.getName();
            if (name.equals("word")) {
                name1 += "doc,docx,";
            } else if (name.equals("excel")) {
                name1 += "xls,xlsx,";
            } else {
                name1 += name + ",";
            }

        }
        List list1 = new ArrayList();
        list1 = getFiles(new File(path).getParent(), list1);
        if (!StringUtils.isEmpty(name1)) {
            for (Object path1 : list1) {
                if (name1.indexOf((path1.toString().substring(path1.toString().lastIndexOf(".") + 1)).toLowerCase() + ",") < 0) {
                    set.add((path1.toString().substring(path1.toString().lastIndexOf(".") + 1)).toLowerCase());
                }
            }
        }
        List<String> list = new ArrayList<String>(set);

        return list;
    }

    public List<String> checkDaDh(Long categoryId, Integer type, String rq, String fieldName, Map map, Long daId, String subTableName) {

        List list = new ArrayList();
        //获取规则项然后去获取值
        List<Map> list1 = new ArrayList<>();
        if (StringUtils.isNotEmpty(rq)) {
            rq = rq.replaceAll("-", "").replaceAll("/", "");
            rq = addZero(rq);
        }
        if (!StringUtils.isEmpty(rq)) {
            list1 = detectionObjectMapper.getDhByRq(rq, SecurityUtils.getTenantCode().toUpperCase(), categoryId);
        }

        if (list1.size() <= 0) {
            list1 = detectionObjectMapper.getDh(rq, SecurityUtils.getTenantCode().toUpperCase(), categoryId);
        }        //组件只需要验证档号字段即可
        if (list1.size() <= 0) {
            list.add("该档案未设置档号规则");
        } else {
            String lx = "";
            if (type.equals(0)) {
                lx = "f";
            } else if (type.equals(1) || type.equals(2)) {
                lx = "v";
            }
            com.alibaba.fastjson2.JSONObject json = tenantCodelistService.getdetail(lx, Long.parseLong(list1.get(0).get("RULEID").toString()));
            //获取档号值
            List ziduanarr = (List) json.get("ziduanarr");
            List fuhaoarr = (List) json.get("fuhaoarr");
            List bulingarr = (List) json.get("bulingarr");
            String dh = "";
            if (type.equals(0) || type.equals(1)) {
                //获取值拼接
                for (int i = 0; i < ziduanarr.size(); i++) {
                    String field = ziduanarr.get(i).toString();
                    //获取值
                    String value = detectionObjectMapper.getDhValue(field, daId, SecurityUtils.getTenantCode().toUpperCase(), type) == null ? "" : detectionObjectMapper.getDhValue(field, daId, SecurityUtils.getTenantCode().toUpperCase(), type);
                    int length = value.length();
                    if (i == (ziduanarr.size() - 1)) {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {

                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value;

                    } else {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value + fuhaoarr.get(i);
                    }

                }
                if (!dh.equals(detectionObjectMapper.getDhValue(fieldName, daId, SecurityUtils.getTenantCode().toUpperCase(), type))) {
                    list.add("档号字段不符合档号规则");
                }

            } else if (type.equals(2)) {
                //卷内件
                Long folderId = detectionObjectMapper.getFolderIdByDaId(daId, SecurityUtils.getTenantCode().toUpperCase());
                // daId=detectionObjectMapper.getFolderIdByDaId(daId,SecurityUtils.getTenantCode().toUpperCase());
                String jianlianjie = json.getString("jianlianjie");
                String jianziduan = json.getString("jianziduan");
                String jianbuling = json.getString("jianbuling");
                //获取值拼接
                for (int i = 0; i < ziduanarr.size(); i++) {
                    String field = ziduanarr.get(i).toString();
                    //获取值
                    //通过daId获取folderId
                    String value = detectionObjectMapper.getDhValue(field, folderId, SecurityUtils.getTenantCode().toUpperCase(), 1) == null ? "" : detectionObjectMapper.getDhValue(field, folderId, SecurityUtils.getTenantCode().toUpperCase(), 1);
                    int length = value.length();
                    if (i == (ziduanarr.size() - 1)) {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - length); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value;

                    } else {
                        if (Integer.parseInt(bulingarr.get(i).toString()) > 0) {
                            if (value.length() < Integer.parseInt(bulingarr.get(i).toString())) {
                                for (int j = 0; j < (Integer.parseInt(bulingarr.get(i).toString()) - value.length()); j++) {
                                    value = "0" + value;
                                }
                            }
                        }
                        dh += value + fuhaoarr.get(i);
                    }

                }
                //拼接最后一位
                dh += jianlianjie;
                String jianValue = detectionObjectMapper.getDhValue(jianziduan, daId, SecurityUtils.getTenantCode().toUpperCase(), type) == null ? "" : detectionObjectMapper.getDhValue(jianziduan, daId, SecurityUtils.getTenantCode().toUpperCase(), type);
                int jianLegth = jianValue.length();
                if (Integer.parseInt(jianbuling) > 0) {
                    if (jianValue.length() < Integer.parseInt(jianbuling)) {
                        for (int j = 0; j < (Integer.parseInt(jianbuling) - jianLegth); j++) {
                            jianValue = "0" + jianValue;
                        }
                    }
                }
                dh += jianValue;
                if (!dh.equals(detectionObjectMapper.getDhValue(fieldName, daId, SecurityUtils.getTenantCode().toUpperCase(), type))) {
                    list.add("档号字段不符合档号规则");
                }


            }


        }


        return list;
    }

    public List<String> getFiles(String path, List list) {

        File file = new File(path);
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
            // 获取路径下的所有文件
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                // 如果还是文件夹 递归获取里面的文件 文件夹
                if (files[i].isDirectory()) {
                    getFiles(files[i].getPath(), list);
                } else {
                    if (!files[i].getName().equals("档案元数据.xml")) {
                        list.add(files[i].getPath());
                    }
                }

            }
        } else {
            if (!file.getName().equals("档案元数据.xml")) {
                list.add(file.getPath());
            }
        }
        return list;
    }

    public List verifyFormatDa(List<DetectionItem> detectionItems, List<DetectionFile> detectionFileList) {
        Set<String> set = new HashSet();

        String name1 = "";
        for (DetectionItem detectionItem : detectionItems) {
            String name = detectionItem.getName();
            if (name.equals("word")) {
                name1 += "doc,docx,";
            } else if (name.equals("excel")) {
                name1 += "xls,xlsx,";
            } else {
                name1 += name + ",";
            }

        }
        if (!StringUtils.isEmpty(name1)) {
            for (DetectionFile detectionFile : detectionFileList) {
                if (name1.indexOf(detectionFile.getDocFileType().toLowerCase() + ",") < 0) {
                    set.add(detectionFile.getDocFileType().toLowerCase());
                }
            }
        }
        List<String> list = new ArrayList<String>(set);

        return list;
    }

    public String getDh(Long daId, Integer type, Long categoryId, String subTableName) {
        //获取档号字段
        String dh = "";
        String dhz = "";
        if ("1".equals(isZt)) {
            dhz = "DH";
        } else {
            String rq = detectionObjectMapper.getFieldNames(daId, subTableName, "rq");

            if (StringUtils.isNotEmpty(rq)) {
                rq = rq.replaceAll("-", "").replaceAll("/", "");
                rq = addZero(rq);
            }
            List<Map> list1 = detectionObjectMapper.getDh(rq, SecurityUtils.getTenantCode().toUpperCase(), categoryId);
            //组件只需要验证档号字段即可
            if (list1.size() <= 0) {
            } else {
                String lx = "";
                if (type.equals(0) || type.equals(2)) {
                    lx = "f";
                } else if (type.equals(1)) {
                    lx = "v";
                }
                JSONObject json = tenantCodelistService.getdetail(lx, Long.parseLong(list1.get(0).get("RULEID").toString()));
                //获取档号值

                dhz = json.getString("jiancunchuziduan");

            }
        }
        if("".equals(dhz)){
            dhz="DH";
        }
        if (type.equals(0) || type.equals(2)) {
            //组件
            dh = detectionObjectMapper.getFieldNames(daId, subTableName, dhz);
        } else if (type.equals(1)) {
            dh = detectionObjectMapper.getFieldNames(daId, subTableName, dhz);

        }


        return dh;
    }

    //字符串不足8位末尾补零
    public String addZero(String str) {
        int length = str.length();
        if (length < 8) {
            int b = 8 - length;
            for (int i = 0; i < b; i++) {
                str += "0";
            }
            return str;
        }
        return str;
    }
    public List<TenantMdataList> getSchemelist(TenantMdataList yqdaMdataList) {
        Long categoryId = yqdaMdataList.getCategoryId();
        TenantCategory tenantCategory = new TenantCategory();
        String groupId = tenantCategoryMapper.selectGroupIdById(categoryId, tenantCategory.getTableName());
        if(!StringUtils.isNotEmpty(groupId)){
            throw new ServiceException("请元数据方案");
        }
        yqdaMdataList.setGroupId(Long.valueOf(groupId));
        List<TenantMdataList> tenantMdataLists = tenantCateMdataListMapper.getSchemelist(yqdaMdataList);
        return tenantMdataLists;
    }

    //判断
    public  boolean IsEncryption(String file,String fileType) throws IOException {
        if(fileType.toUpperCase().equals("PDF")){
            return PdfIsEncryption(file);
        }else if (fileType.toUpperCase().equals("JPG")||fileType.toUpperCase().equals("PNG")){
            return isImageEncrypted(file);
        }else if (fileType.toUpperCase().equals("XLS")||fileType.toUpperCase().equals("XLSX")){
            return isExcelEncrypted(file);
        }else if (fileType.toUpperCase().equals("PPT")){
            return isPptProtected(file);
        }else if (fileType.toUpperCase().equals("DOC")||fileType.toUpperCase().equals("DOCX")){
            return isWordEncrypted(file);
        }else if (fileType.toUpperCase().equals("MP3")){
            return isMP3Decodable(file);
        }else{
            return false;
        }

    }

    //判断pdf是否加密
    public  Boolean PdfIsEncryption(String file){
        PdfReader reader = null;
        try {
            reader = new PdfReader(file);
            return reader.isEncrypted();
        }catch (Exception e){
            e.printStackTrace();
            return true;
        }finally {
            if(reader !=null){
                reader.close();
            }
        }
        // return true;
    }


    //图片是否加解密
    public  Boolean  isImageEncrypted(String imagePath) {
        try {
            BufferedImage image = ImageIO.read(new File(imagePath));
            return image == null;
        } catch (IOException e) {
            // 解码过程中发生了异常，可能图片已加密或文件损坏
            return true;
        }
    }

    //判断excel是否加密
    public  boolean isExcelEncrypted(String filePath) {
        try {
            WorkbookFactory.create(new File(filePath));
            // 如果上面的代码没有抛出异常，则文件不加密
            return false;
        } catch (Exception e) {
            // 如果抛出EncryptedDocumentException，则文件加密
            return true;
        }
    }

    public  boolean isWordEncrypted(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath)) {
            // 尝试使用Apache POI打开.docx文件
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            // 如果能成功打开，则认为文件未加密
            workbook.close(); // 关闭Workbook
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            // 如果捕获到EncryptedDocumentException异常，则认为文件被加密
            // 注意：Apache POI的XSSFWorkbook类本身不直接抛出EncryptedDocumentException，
            // 这里只是作为示例。实际上，你可能需要捕获其他类型的异常，如IOException，
            // 并根据异常信息或文档内容来判断是否加密。
            return true;
        }
    }

    public  boolean isPptProtected(String path) {
        File file=new File(path);
        boolean isProtected = false;
        HSLFSlideShow ppt=null;
        try (FileInputStream fis = new FileInputStream(file)) {
            ppt = new HSLFSlideShow(fis);
            ppt.getPageSize();
            ppt.close();
        } catch (Exception e){
            if(e.getMessage().toLowerCase().indexOf("encrypted")!=-1){
                isProtected = true;
            }
        } finally {
            if(ppt!=null){
                IoUtil.close(ppt);
            }
            return isProtected;
        }
    }


    public   boolean isMP3Decodable(String path) {
        try {
            File mp3File=new File(path);
            AudioFormat format = AudioSystem.getAudioFileFormat(mp3File).getFormat();
            SourceDataLine line = AudioSystem.getSourceDataLine(format);
            line.open(format);
            line.start();
            line.close();
            return true;
        } catch (IOException | LineUnavailableException | UnsupportedAudioFileException e) {
            return false;
        }
    }


}
